package com.homestead.controller;

import com.homestead.bo.CreateOrgBo;
import com.homestead.constant.RedisLockKeyConstant;
import com.homestead.controller.ao.CreateOrgAo;
import com.homestead.enums.CommonErrorCode;
import com.homestead.exception.OrgInfoException;
import com.homestead.resp.CommonResponse;
import com.homestead.result.RedisLockResult;
import com.homestead.service.OrgInfoService;
import com.homestead.utils.CommonResponseUtil;
import com.homestead.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author HanBin_Yang
 * @since 2021/4/10 18:17
 */
@RestController
@RequestMapping("/org")
@Api(tags = {"组织架构"})
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class OrgInfoController {
    private final OrgInfoService orgInfoService;
    private final RedissonClient redissonClient;

    @PostMapping("/create")
    @ApiOperation(value = "创建组织", httpMethod = "POST")
    public CommonResponse<Boolean> create(@RequestBody CreateOrgAo ao) throws Exception {
        CreateOrgBo bo = ao.convert();
        RLock writeLock = redissonClient.getReadWriteLock(RedisLockKeyConstant.WRITE_COUPON_THEME_ADAPT_ORG_DATABASE).writeLock();
        RedisLockResult<Boolean> redisLockResult = RedisUtil.executeTryLock(writeLock, 0, 2, TimeUnit.MINUTES, () -> {
            orgInfoService.create(bo);
            return true;
        });

        if (redisLockResult.isFailure()) {
            throw new OrgInfoException(CommonErrorCode.SYSTEM_BUSY);
        }

        return CommonResponseUtil.successObj(true);
    }
}
